﻿#include "HardWareMonitor.h"
#include "ui_HardWareMonitor.h"

HardWareMonitor::HardWareMonitor(QWidget *parent)
    : QWidget(parent)
{
    ui = new Ui::HardWareMonitor();
    ui->setupUi(this);
    ui->cpuInfo->setType(1);
    ui->memoryInfo->setType(1);
    m_pTimer = new QTimer(this);
    connect(m_pTimer, &QTimer::timeout, this, &HardWareMonitor::slotHandleTimeout);
}

HardWareMonitor::~HardWareMonitor()
{
    delete ui;
}

void HardWareMonitor::on_pushButton_clicked()
{
    this->close();
}
void HardWareMonitor::slotHandleTimeout()
{
    double cpuValue = getCPUUseage();
    MEMORYSTATUSEX statusex;
    statusex.dwLength = sizeof(statusex);
    GlobalMemoryStatusEx(&statusex);
    int memoryValue = statusex.dwMemoryLoad;
    if (cpuValue < 0 || cpuValue>100)
        return;
    ui->memoryInfo->setNum(memoryValue);
    ui->cpuInfo->setNum(qRound(cpuValue));
}
double HardWareMonitor::getCPUUseage()
{
    if (GetSystemTimes(&_idle_time, &_kernel_time, &_user_time) == 0)
    {
        printf("get cpu usage failed.\n");
        return 0;
    }
    int idle = (int)CompareFileTime(_old_idle_time, _idle_time);
    int kernel = (int)CompareFileTime(_old_kernel_time, _kernel_time);
    int user = (int)CompareFileTime(_old_user_time, _user_time);
    double rate = (double)(kernel + user - idle) * 100 / (kernel + user);
    _old_idle_time = _idle_time;
    _old_kernel_time = _kernel_time;
    _old_user_time = _user_time;
    return rate;
}
__int64 HardWareMonitor::CompareFileTime(FILETIME	time1, FILETIME time2)
{
    __int64 a = (__int64)time1.dwHighDateTime << 32 | time1.dwLowDateTime;
    __int64 b = (__int64)time2.dwHighDateTime << 32 | time2.dwLowDateTime;
    return(b - a);
}
void HardWareMonitor::closeEvent(QCloseEvent */*event*/)
{
    this->hide();
}
void HardWareMonitor::hideEvent(QHideEvent */*event*/)
{
    if(m_pTimer!=NULL)
        m_pTimer->stop();
}
void HardWareMonitor::showEvent(QShowEvent */*event*/)
{
    if (m_pTimer != NULL)
        m_pTimer->start(1000);
}
